package com.zl.zlproject.model.net.engine.intercepter;

import android.content.Context;

import com.zl.zlproject.R;
import com.zl.zlproject.model.net.bean.BaseNetBean;
import com.zl.zlproject.utils.MyToast;
import com.zl.zlproject.utils.NetUtils;
import com.zl.zlproject.utils.ThreadUtils;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import retrofit2.HttpException;


/**
 * Created by 郑磊 on 2018/5/30.
 */

public abstract class HttpResult<T> implements Observer<T> {
    private Context mContext;

    public HttpResult(Context context) {
        mContext = context;
    }

    @Override
    public void onSubscribe(Disposable d) {

    }

    @Override
    public void onNext(T t) {
        if (!(t instanceof BaseNetBean)) {
            onFailed();
            return;
        }
        BaseNetBean baseNetBean = (BaseNetBean) t;
        if (baseNetBean.code == 0) {
            onSuccess(t);
            return;
        }
        onFailed();
        if (ThreadUtils.isMainThread()) {
            MyToast.show(mContext, baseNetBean.msg);
        }
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        onFailed();
        if (!ThreadUtils.isMainThread()) {   //不在主线程
            return;
        }
        if (!NetUtils.isConnected(mContext)) {   //没有网络
            MyToast.show(mContext, mContext.getString(R.string.no_network));
            return;
        }

        if (e instanceof SocketTimeoutException) {
            MyToast.show(mContext, mContext.getString(R.string.time_out_error));
        } else if (e instanceof ConnectException || e instanceof SocketException || e instanceof HttpException) {
            MyToast.show(mContext, mContext.getString(R.string.server_connection_failed));
        } else if (e instanceof UnknownHostException) {
            MyToast.show(mContext, mContext.getString(R.string.server_host_address_error));
        } else {
            MyToast.show(mContext, mContext.getString(R.string.unknown_error));
        }
    }

    @Override
    public void onComplete() {

    }


    protected abstract void onFailed();

    protected abstract void onSuccess(T t);


}
